const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
console.log(numCPUs);
if(cluster.isMaster) {

	// Keep track of http requests
	let numReqs = 0;
	// Count requests
	function messageHandler(msg) {
		if(msg.cmd && msg.cmd === 'notifyRequest') {
			numReqs += 1;
		}
	}

	// Start workers and listen for messages containing notifyRequest
	
	for(let i = 0; i < 5; i++) {
		cluster.fork();
	}
	for(const id in cluster.workers) {
		console.log(cluster.workers[id]);
		cluster.workers[id].on('message', messageHandler);
	}

} else {

	// Worker processes have a http server.
	http.Server((req, res) => {
		res.writeHead(200);
		res.end('hello world\n');

		// notify master about the request
		process.send({
			cmd: 'notifyRequest'
		});
	}).listen(8000);
}